package com.itlong.cloud.controller.value;

import com.fasterxml.jackson.core.type.TypeReference;
import com.itlong.cloud.POJO.DTO.operate.OperateAnalyseListDTO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.operate.OperateAnalyseListVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.enumerate.FileCatalogEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.PropertyErrorCodeEnum;
import com.itlong.cloud.project.operate.IOperateAnalyseServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.file.UploadFileUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *      运营-运营分析控制器
 * </desc>
 *
 * @createDate 2019/06/03
 */
@RestController
@RequestMapping("/propertyValue/operateAnalyse")
@RefreshScope
public class OperateAnalyseController extends BaseController{

    @Autowired
    IOperateAnalyseServiceClient iOperateAnalyseServiceClient;


    @Value("${" + PlatformConstants.FILE_FTP_HOST + "}")
    public String FILE_FTP_HOST;

    @Value("${" + PlatformConstants.FILE_FTP_PORT + "}")
    public String FILE_FTP_PORT;

    @Value("${" + PlatformConstants.FILE_FTP_USERNAME + "}")
    public String FILE_FTP_USERNAME;

    @Value("${" + PlatformConstants.FILE_FTP_PASSWORD + "}")
    public String FILE_FTP_PASSWORD;

    @Value("${" + PlatformConstants.FILE_ACCESS_URL + "}")
    public String FILE_ACCESS_URL;

    @Value("${" + PlatformConstants.PROJECT_STATIC_FILE_PATH + "}")
    public String PROJECT_STATIC_FILE_PATH;

    /**
     * <desc>
     *      获取分页列表
     * </desc>
     *
     * @param dto
     * @return
     * @author Jiaqi.X
     * @createDate 2019/05/29
     */
    @RequestMapping(path = "list",method = RequestMethod.POST)
    @ResponseBody
    @AuthAccessRequired
    public Object list(OperateAnalyseListDTO dto){
        MessageVO messageVO;
        try{
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            dto= HttpProtocolUtil.parseRequestParamToDTO(OperateAnalyseListDTO.class,request);
            messageVO=new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),iOperateAnalyseServiceClient.list(dto));
        }catch (Exception e){
            throw new DataAccessException("【运营_物业增值_运营分析list】获取列表失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      导出运营分析表
     * </desc>
     *
     * @param dto
     * @return 标准格式化响应结果
     * @author Jiaqi.X
     * @createDate 2019/06/03
     */
    @ResponseBody
    @AuthAccessRequired
    @PostMapping("export")
    public Object export(OperateAnalyseListDTO dto){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            dto= HttpProtocolUtil.parseRequestParamToDTO(OperateAnalyseListDTO.class,request);
            Map<String,Object> result = iOperateAnalyseServiceClient.list(dto);
            List<OperateAnalyseListVO> vos = JsonUtil.decode(JsonUtil.toJSON(result.get("rows")), new TypeReference<List<OperateAnalyseListVO>>() {});
            if (vos == null || vos.isEmpty()) {
                return new MessageVO(PropertyErrorCodeEnum.EXPORT_DATA_EMPTY_ERR.getErrorCode());
            }
            String[] title = {"项目编号",
                    "项目名称",
                    "所在地",
                    "收费月份",
                    "物业增值",
                    "房屋总数",
                    "已入住",
                    "入住率",
                    "应收总额",
                    "实收总额",
                    "分润总额",
                    "收缴率"
            };
            short rowHeight= 420;
            //创建excel工作簿
            HSSFWorkbook workbook=new HSSFWorkbook();
            //创建工作表sheet并设置简单格式
            HSSFSheet sheet=workbook.createSheet();
            sheet.setDefaultColumnWidth(15);
            //创建第一行
            HSSFRow row=sheet.createRow(0);
            row.setHeight(rowHeight);
            HSSFCell cell=null;
            //插入第一行数据的表头
            for (int i = 0; i < title.length; i++) {
                cell = row.createCell(i);
                cell.setCellValue(title[i]);
            }
            //写入数据
            int i = 0;
            for (int index = 0; index < vos.size(); index++) {
                OperateAnalyseListVO vo = vos.get(index);
                int rowIndex = i + 1; // 第一行已为标题行
                HSSFRow dataRow = sheet.createRow(rowIndex);
                dataRow.setHeight(rowHeight);
                HSSFCell noteCell = dataRow.createCell(0);
                noteCell.setCellValue(vo.getProjectId());
                noteCell = dataRow.createCell(1);
                noteCell.setCellValue(vo.getProjectName());
                noteCell = dataRow.createCell(2);
                noteCell.setCellValue(vo.getAddress());
                noteCell = dataRow.createCell(3);
                noteCell.setCellValue(vo.getMonth());
                noteCell = dataRow.createCell(4);
                switch (vo.getPropertyValueType()){
                    case "0":
                        noteCell.setCellValue("未开通");
                        break;
                    case "1":
                        noteCell.setCellValue("已开通");
                        break;
                }
                noteCell = dataRow.createCell(5);
                noteCell.setCellValue(vo.getRoomTotal());
                noteCell = dataRow.createCell(6);
                noteCell.setCellValue(vo.getHouseholdTotal());
                noteCell = dataRow.createCell(7);
                noteCell.setCellValue(vo.getInRate());
                noteCell = dataRow.createCell(8);
                noteCell.setCellValue(vo.getDueAmount());
                noteCell = dataRow.createCell(9);
                noteCell.setCellValue(vo.getPaidAmount());
                noteCell = dataRow.createCell(10);
                noteCell.setCellValue(vo.getShareTotal());
                noteCell = dataRow.createCell(11);
                noteCell.setCellValue(vo.getColectionRate());
                i++;
            }
            String fileName = String.format("%s_OperateAnalyse_%s.xls",
                    dto.getProjectId(),
                    DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS"));
            fileName = URLEncoder.encode(fileName, "UTF-8");
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            workbook.write(os);
            byte[] content = os.toByteArray();
            InputStream exportFileStream = new ByteArrayInputStream(content);
            String exportFileUrl = uploadFile(exportFileStream,fileName);
            if (StringUtils.isBlank(exportFileUrl)){
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_EXPORT_FILE_SAVE_ERR.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), (Object) exportFileUrl);
        } catch (Exception e) {
            throw new DataAccessException("【物业-物业缴费】导出物业费表单失败",e);
        }
    }


    /**
     * <desc>
     *      Ftp上传文件，返回Url.
     * </desc>
     *
     * @param inputStream 文件流
     * @param fileName 文件名称
     * @return 文件上传成功后会返回Url,否则返回空
     * @author Jiaqi.X
     * @createDate 2018/08/17
     */
    private String uploadFile(InputStream inputStream, String fileName) throws IOException {
        String fileUrl = "";
        String fileType = StringHandlerUtil.copySubStr(fileName, fileName.lastIndexOf('.') + 1, fileName.length());
        UploadFileUtil.UploadFile uploadFileUtil = new UploadFileUtil().new UploadFile(
                FILE_FTP_HOST,
                FILE_FTP_USERNAME,
                FILE_FTP_PASSWORD,
                FILE_FTP_PORT,
                inputStream,
                fileType,
                FILE_ACCESS_URL,
                FileCatalogEnum.PROPERTY_METER_INFO_FILE.getType()
        );
        Map<String, Object> resultMap = UploadFileUtil.uploadFile(uploadFileUtil);
        Boolean returnCode = (Boolean)resultMap.get("returnCode");
        if (returnCode == false){
            return fileUrl;
        }
        fileUrl = resultMap.get("accessPath").toString();
        return fileUrl;
    }
}
